package Java.com.wang.other;

public class linkList<T> {

    private Node<T> head;
    private int Length;

    public linkList()
    {
        Length=0;
        head=new Node<T>(null);
    }


    public Node<T> getHead()
    {
        return head;
    }

    public boolean add(T obj,int pos)
    {
        if((pos<1||pos>Length+1))
        {
            System.out.println("pos值不合法");
            return false;
        }
        int num=1;
        Node<T> p=head,q=head.next;
        while(num<pos)
        {
            p=q;
            q=q.next;
            num++;
        }
        p.next=new Node<T>(obj,q);
        Length++;
        return true;
    }

    public boolean isEmpty()
    {
        return Length==0;
    }


    public int size()
    {
        return Length;
    }

    public void nextOrder()
    {
        Node<T> p=head.next;
        while(p!=null)
        {
            System.out.println(p.data);
            p=p.next;
        }
    }

    public void pOrder(int pos)
    {
        Node<T> p=head.next;
        int i=0;
        if(p!=null) {
            while (i < pos - 1) {
                p = p.next;
                i++;
            }
            System.out.println(p.data);
        }
    }
    //单链表的删除
    public T remove (int pos ){
        if(isEmpty()){
            System.out.println("链表为空");
            return null;
        }
        else{
            if(pos<1||pos>(Length+1)){
                System.out.println("pos值不合法");
                return  null;
            }
            int num=1;
            Node<T>  p=head;
            Node<T>  q=head.next;
            while(num<pos){
                p=q;
                q=q.next;
                num++;
            }
            p.next = q.next;
            Length--;
            return q.data;
        }
    }

    //单链表的查找
    public int find(T obj){
        if(isEmpty()){
            System.out.println("链表为空");
            return -1;
        }
        int num=1;
        Node<T>  p =head.next;
        while(p!=null){
            if (p.data.equals(obj)==false){
                p=p.next;
                num++;
            }
            else break;
        }
        if(p==null) {
            return -1;
        }
        return num;
    }

}

